﻿namespace EyeOpen.EasyEntityFramework.Shell
{
	using System;
	using System.Data.Entity;

	using EyeOpen.EasyEntityFramework.Data;
	using EyeOpen.EasyEntityFramework.Domain;

	internal class Program
	{
		internal static void Main(string[] args)
		{
			const string SqlCeConnectionString = "Data Source = Accounting.sdf";
			const string SqlServerConnectionString = @"Server = .\SQL2008; Initial Catalog = Accounting.sdf; Integrated security = true";

			const string ProviderName = DbProviders.SqlCe;
			const string ConnectionString = SqlCeConnectionString;

			////The derived DbContext need:
			////Provider name: the unique ADO.NET mnemonic string that reference
			////a DBMS as SQLServer, SQLCe, MySQL etct..
			////ConnectionString: the full connection string to the database
			using (var uow = new AccountingContext(ProviderName, ConnectionString))
			{
				////Check if database exitst, if so delete it
				DeleteDatabaseIfExists(uow);

				////Create the database using the schema produced by EntityFramework
				CreateDatabaseFromMapping(uow);

				AddCustomer(uow);
			}

			using (var uow = new AccountingContext(ProviderName, ConnectionString))
			{
				foreach (var customer in uow.CustomerSet)
				{
					Console.WriteLine("Customer \n\t{{ \n\t\tId = {0} \n\t\tName = {1}\n\t}}", customer.Id, customer.Name);
				}
			}

			Console.ReadLine();
		}

		private static void CreateDatabaseFromMapping(DbContext uow)
		{
			////Here the T-SQL generated from EF, check it using Micrsoft SQL Profiler

			////create table [dbo].[Customer] (
			////[Id] [uniqueidentifier] not null,
			////[Name] [nvarchar](max) null,
			////primary key ([Id])
			////);
			////create table [dbo].[EdmMetadata] (
			//// [Id] [int] not null identity,
			////[ModelHash] [nvarchar](max) null,
			////primary key ([Id])
			////);

			uow.Database.Create();
		}

		private static void DeleteDatabaseIfExists(DbContext uow)
		{
			if (uow.Database.Exists())
			{
				uow.Database.Delete();
			}
		}

		private static void AddCustomer(AccountingContext uow)
		{
			var customer = new Customer { Id = Guid.NewGuid(), Name = "Bill" };

			uow.CustomerSet.Add(customer);

			uow.SaveChanges();
		}
	}
}